﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Drawing;
using Omu.Drawing;
using Tasker.Common;
using Tasker.Infrastructure;

namespace Tasker.Services
{
    public class PictureManagerService : IPictureManagerService
    {
        public string SaveTempPicture(Stream inputStream, out int width, out int height)
        {
            string fileName = Guid.NewGuid().ToString() + ".jpg";
            var filePath = Path.Combine(DirectoryHelper.TempFolder, fileName);
            using (var image = Image.FromStream(inputStream))
            {
                var resized = Imager.Resize(image, 800, 600, true);

                //Imager.Save(filePath, resized, inputStream.Ty);
                Imager.SaveJpeg(filePath, resized);

                width = resized.Width;
                height = resized.Height;
                return fileName;
            }
        }

        public void MakePictures(string fileName, int iWidth, int iHeight, int x, int y, int width, int height)
        {
            using (var image = Image.FromFile(Path.Combine(DirectoryHelper.TempFolder, fileName)))
            {
                var img = Imager.Resize(image, iWidth, iHeight, true);
                if (width == iWidth) width--;
                if (height == iHeight) height--;
                img = Imager.Crop(img, new Rectangle(x, y, width, height));
                var resized = Imager.Resize(img, 300, 300, true);
                var small = Imager.Resize(img, 100, 100, true);
                Imager.SaveJpeg(Path.Combine(DirectoryHelper.UserPhotosDirectory, fileName), resized);
                Imager.SaveJpeg(Path.Combine(DirectoryHelper.UserPhotoThumbsDirectory, fileName), small);
            }
        }

        public void Delete(string fileName)
        {
            File.Delete(Path.Combine(DirectoryHelper.UserPhotosDirectory, fileName));
            File.Delete(Path.Combine(DirectoryHelper.UserPhotoThumbsDirectory, fileName));
        }
    }
}
